<template>
  <div class="inspection-items-container">
    <!-- 页面标题和描述 -->
    <div class="page-header">
      <h2>检验项指标库</h2>
      <p class="description">
        当您在【基础设置-全部商品-添加检验项目-添加检验内容】时，可直接从此库中检索指标内容
      </p>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <a-button type="primary" @click="showAddItemModal">
        <template #icon><Plus /></template>
        添加检验项目
      </a-button>
      <a-button @click="batchDelete" :disabled="selectedItems.length === 0">
        <template #icon><Trash2 /></template>
        批量删除
      </a-button>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧分类列表 -->
      <div class="left-panel">
        <div class="classification-header">
          <h3>分类</h3>
          <a-button type="link" @click="showAddCategoryModal">
            <template #icon><Plus /></template>
            添加分类
          </a-button>
        </div>

        <div class="classification-list">
          <div
            v-for="category in categories"
            :key="category.id"
            :class="[
              'classification-item',
              { active: selectedCategory?.id === category.id },
            ]"
            @click="selectCategory(category)"
          >
            <span class="category-name">{{ category.name }}</span>
            <span class="item-count"
              >({{ getCategoryItemCount(category.id) }})</span
            >
          </div>
        </div>
      </div>

      <!-- 右侧检验项目列表 -->
      <div class="right-panel">
        <div class="items-header">
          <h3>{{ selectedCategory?.name || '请选择分类' }}</h3>
          <a-input-search
            v-model:value="searchKeyword"
            placeholder="搜索检验项目"
            style="width: 300px"
            @search="handleSearch"
          />
        </div>

        <a-table
          :columns="columns"
          :data-source="filteredItems"
          :row-selection="rowSelection"
          :pagination="false"
          size="middle"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <a-space>
                <a-button type="link" size="small" @click="editItem(record)">
                  <template #icon><UserRoundPen /></template>
                  编辑
                </a-button>
                <a-popconfirm
                  title="确定要删除这个检验项目吗？"
                  @confirm="deleteItem(record.id)"
                >
                  <a-button type="link" size="small" danger>
                    <template #icon><Trash2 /></template>
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 添加/编辑检验项目模态框 -->
    <InspectionItemModal
      v-model:open="showItemModal"
      :item="currentItem"
      @save="handleSaveItem"
    />

    <!-- 添加分类模态框 -->
    <CategoryModal
      v-model:open="showCategoryModal"
      @save="handleSaveCategory"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { Plus, Trash2, UserRoundPen } from '@vben/icons';
import InspectionItemModal from './components/InspectionItemModal.vue';
import CategoryModal from './components/CategoryModal.vue';

// 类型定义
interface InspectionCategory {
  id: string;
  name: string;
  description?: string;
}

interface InspectionItem {
  id: string;
  name: string;
  unit: string;
  standardName: string;
  description: string;
  categoryId: string;
  referenceValues: {
    cat: {
      juvenile: { min: number; max: number };
      adult: { min: number; max: number };
      elderly: { min: number; max: number };
    };
    dog: {
      juvenile: { min: number; max: number };
      adult: { min: number; max: number };
      elderly: { min: number; max: number };
    };
    other: {
      juvenile: { min: number; max: number };
      adult: { min: number; max: number };
      elderly: { min: number; max: number };
    };
  };
}

// 响应式数据
const categories = ref<InspectionCategory[]>([
  { id: '1', name: '血常规' },
  { id: '2', name: '尿常规' },
  { id: '3', name: '生化检验' },
  { id: '4', name: '内分泌及快速检测' },
  { id: '5', name: '电解质及血液气体分析' },
]);

const inspectionItems = ref<InspectionItem[]>([
  {
    id: '1',
    name: '白细胞计数',
    unit: '10^9/L',
    standardName: 'WBC',
    description: '血液中白细胞的数量',
    categoryId: '1',
    referenceValues: {
      cat: {
        juvenile: { min: 5.5, max: 19.5 },
        adult: { min: 5.5, max: 19.5 },
        elderly: { min: 5.5, max: 19.5 },
      },
      dog: {
        juvenile: { min: 6.0, max: 17.0 },
        adult: { min: 6.0, max: 17.0 },
        elderly: { min: 6.0, max: 17.0 },
      },
      other: {
        juvenile: { min: 5.0, max: 18.0 },
        adult: { min: 5.0, max: 18.0 },
        elderly: { min: 5.0, max: 18.0 },
      },
    },
  },
  {
    id: '2',
    name: '红细胞计数',
    unit: '10^12/L',
    standardName: 'RBC',
    description: '血液中红细胞的数量',
    categoryId: '1',
    referenceValues: {
      cat: {
        juvenile: { min: 5.0, max: 10.0 },
        adult: { min: 5.0, max: 10.0 },
        elderly: { min: 5.0, max: 10.0 },
      },
      dog: {
        juvenile: { min: 5.5, max: 8.5 },
        adult: { min: 5.5, max: 8.5 },
        elderly: { min: 5.5, max: 8.5 },
      },
      other: {
        juvenile: { min: 4.5, max: 9.5 },
        adult: { min: 4.5, max: 9.5 },
        elderly: { min: 4.5, max: 9.5 },
      },
    },
  },
]);

const selectedCategory = ref<InspectionCategory | null>(null);
const selectedItems = ref<string[]>([]);
const searchKeyword = ref('');
const showItemModal = ref(false);
const showCategoryModal = ref(false);
const currentItem = ref<InspectionItem | null>(null);

// 表格列定义
const columns = [
  {
    title: '指标名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '指标单位',
    dataIndex: 'unit',
    key: 'unit',
  },
  {
    title: '标准名称',
    dataIndex: 'standardName',
    key: 'standardName',
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
  },
];

// 计算属性
const filteredItems = computed(() => {
  let items = inspectionItems.value;

  if (selectedCategory.value) {
    items = items.filter(
      (item) => item.categoryId === selectedCategory.value!.id,
    );
  }

  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    items = items.filter(
      (item) =>
        item.name.toLowerCase().includes(keyword) ||
        item.standardName.toLowerCase().includes(keyword) ||
        item.description.toLowerCase().includes(keyword),
    );
  }

  return items;
});

const rowSelection = computed(() => ({
  selectedRowKeys: selectedItems.value,
  onChange: (selectedRowKeys: string[]) => {
    selectedItems.value = selectedRowKeys;
  },
}));

// 方法
const selectCategory = (category: InspectionCategory) => {
  selectedCategory.value = category;
  selectedItems.value = [];
};

const getCategoryItemCount = (categoryId: string) => {
  return inspectionItems.value.filter((item) => item.categoryId === categoryId)
    .length;
};

const showAddItemModal = () => {
  currentItem.value = null;
  showItemModal.value = true;
};

const editItem = (item: InspectionItem) => {
  currentItem.value = { ...item };
  showItemModal.value = true;
};

const handleSaveItem = (item: InspectionItem) => {
  if (currentItem.value) {
    // 编辑模式
    const index = inspectionItems.value.findIndex((i) => i.id === item.id);
    if (index !== -1) {
      inspectionItems.value[index] = item;
    }
  } else {
    // 新增模式
    item.id = Date.now().toString();
    inspectionItems.value.push(item);
  }
  showItemModal.value = false;
};

const deleteItem = (id: string) => {
  const index = inspectionItems.value.findIndex((item) => item.id === id);
  if (index !== -1) {
    inspectionItems.value.splice(index, 1);
  }
};

const batchDelete = () => {
  inspectionItems.value = inspectionItems.value.filter(
    (item) => !selectedItems.value.includes(item.id),
  );
  selectedItems.value = [];
};

const showAddCategoryModal = () => {
  showCategoryModal.value = true;
};

const handleSaveCategory = (category: InspectionCategory) => {
  if (!category.id) {
    category.id = Date.now().toString();
    categories.value.push(category);
  }
  showCategoryModal.value = false;
};

const handleSearch = () => {
  // 搜索逻辑已在 computed 中处理
};

// 初始化
onMounted(() => {
  if (categories.value.length > 0) {
    selectCategory(categories.value[0]);
  }
});
</script>

<style scoped>
.inspection-items-container {
  padding: 24px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
}

.description {
  color: #666;
  margin: 0;
  font-size: 14px;
}

.action-buttons {
  margin-bottom: 24px;
  display: flex;
  gap: 12px;
}

.main-content {
  flex: 1;
  display: flex;
  gap: 24px;
  min-height: 0;
}

.left-panel {
  width: 280px;
  background: #fafafa;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  flex-direction: column;
}

.classification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.classification-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.classification-list {
  flex: 1;
  overflow-y: auto;
}

.classification-item {
  padding: 12px 16px;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 4px;
  transition: all 0.2s;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.classification-item:hover {
  background: #f0f0f0;
}

.classification-item.active {
  background: #e6f7ff;
  color: #1890ff;
}

.category-name {
  font-weight: 500;
}

.item-count {
  color: #999;
  font-size: 12px;
}

.right-panel {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  display: flex;
  flex-direction: column;
}

.items-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.items-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

:deep(.ant-table) {
  flex: 1;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}
</style>
